/*
 * Galaxium Messenger
 * Copyright (C) 2007 Ben Motmans <ben.motmans@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.IO;
using System.Collections.Generic;

using NDesk.DBus;
using org.freedesktop.DBus;

using Anculus.Core;
using Galaxium.Core;

namespace Galaxium.Client
{
	/// <summary>
	/// Song information backend used to obtain information from the exaile
	/// media player.
	/// </summary>
	public sealed class ExaileSongInformationBackend : AbstractSongInformationBackend
	{
		const string bus = "org.exaile.DBusInterface";
		const string objectPath = "/DBusInterfaceObject";
		
		private IExailePlayer player;
		private bool _dbus;
		
		public override string Name
		{
			get { return "Exaile Music Player"; }
		}

		private IExailePlayer FindExaileInstance ()
		{
			if (!Bus.Session.NameHasOwner (bus))
				return null;

			return Bus.Session.GetObject<IExailePlayer>(bus, new ObjectPath (objectPath));
		}

		public override bool IsAvailable ()
		{
			if (!_dbus)
				return false;
			
			try {
				player = FindExaileInstance ();
			} catch {}

			return player != null;
		}

		public override SongInformation GetCurrentSong ()
		{
			try {
				byte pos = player.current_position ();
				
				if (pos == (byte)0)
					return null;

				int length = ParseLengthString (player.get_length ());
				
				string title = player.get_title ();
				string album = player.get_album ();
				string artist = player.get_artist ();

				SongInformation info = new SongInformation (artist, title, album, length);
				return info;
			} catch {
				return null;
			}
		}

		public override void Initialize ()
		{
			try
			{
				BusG.Init ();
				_dbus = true;
			}
			catch
			{
			}
		}

		public override void Unload ()
		{
		}
		
		[Interface ("org.exaile.DBusInterface")]
		interface IExailePlayer
		{
			string get_album ();
			string get_artist ();
			string get_title ();
			string get_length ();

			byte current_position ();
		}
		
		delegate void StateChangedHandler ();
	}
}